package com.whccb.apps.office.document.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.bpmn.engine.servicetask.ServiceDelegate;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.CMSUtil;
import com.whccb.apps.office.document.util.DictUtil;

public class CreateUrlCmsServiceAtFw extends ServiceDelegate {

	public String getDescription() {
		return "发文流程结束后，自动发布CMS内容，采用URL方式。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public boolean execute(ProcessExecutionContext pec) throws Exception {

		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(pec.getProcessInstance().getId());
		if (paramMap != null && !paramMap.isEmpty()) {

			String boName = paramMap.get("BONAME") != null ? paramMap.get("BONAME").toString() : "";
			String zhmoduleid = paramMap.get("ZHCMSMODULEID") != null ? paramMap.get("ZHCMSMODULEID").toString() : "";
			String fhmoduleid = paramMap.get("FHCMSMODULEID") != null ? paramMap.get("FHCMSMODULEID").toString() : "";
			String gxhmoduleid = paramMap.get("GXHCMSMODULEID") != null ? paramMap.get("GXHCMSMODULEID").toString() : "";
			String msgtype = paramMap.get("CMSMSGTYPE") != null ? paramMap.get("CMSMSGTYPE").toString() : "";
			String cmsTaskDefId = paramMap.get("CMSURLTASKDEFID") != null ? paramMap.get("CMSURLTASKDEFID").toString() : "";
			String formDefId = paramMap.get("CMSFORMDEFID") != null ? paramMap.get("CMSFORMDEFID").toString() : "";

			BO bo = SDK.getBOAPI().getByProcess(boName, pec.getProcessInstance().getId());

			if (bo != null) {
				String zwPdfUrl = bo.getString("PDFURL");
				if (StringUtils.isNotBlank(zwPdfUrl)) {
					String moduleid = "";
					String userDeptid = bo.getString("USERDEPTID");
					// 发文流程需要判断是总行发文/分行发文/管辖行发文.然后写到不同的cms区域。
					String at = "@getDeptExtInfo(@getSuperDept(" + userDeptid + "),ORGCATEGORY)";
					String deptType = SDK.getRuleAPI().executeAtScript(at);
					
					if (ODConstant.ZH_FLAG.equals(deptType)) {// 总行
						moduleid = zhmoduleid;
					}
					if (ODConstant.FH_FLAG.equals(deptType)) {// 分行
						moduleid = fhmoduleid;
					}
					if (ODConstant.GXH_FLAG.equals(deptType)) {// 管辖行
						moduleid = gxhmoduleid;
					}

					String title = "";
					if (StringUtils.isNotBlank(bo.getString("ODTYPE"))) {
						title = title + "<" + DictUtil.getDictValue("WHBK.OD.ODTYPE", bo.getString("ODTYPE")) + ">";
					}

					if (StringUtils.isNotBlank(bo.getString("SUBJECT"))) {
						title = title + bo.getString("SUBJECT");
					}
					
					title = SDK.getRuleAPI().executeAtScript("@substring(" + title + ",0,100)");
					
					if (StringUtils.isNotBlank(moduleid)) {
						String taskInstId = "";
						List<TaskInstance> taskList = SDK.getTaskQueryAPI()
								.processInstId(pec.getProcessInstance().getId()).activityDefId(cmsTaskDefId)
								.addQuery("TASKSTATE !=", "9").list();
						
						if (CollectionUtils.isNotEmpty(taskList)) {
							taskInstId = taskList.get(0).getId();

						} else {
							List<HistoryTaskInstance> hisTaskList = SDK.getHistoryTaskQueryAPI()
									.processInstId(pec.getProcessInstance().getId()).activityDefId(cmsTaskDefId)
									.addQuery("TASKSTATE !=", "9").list();
							if (hisTaskList != null && !hisTaskList.isEmpty() && hisTaskList.size() > 0) {
								taskInstId = hisTaskList.get(0).getId();
							}
						}
						List<String> teamList = new ArrayList<String>();
						String fileToStr = bo.getString("FILETO");
						String fileCcStr = bo.getString("FILECC");
						if (StringUtils.isNotBlank(fileToStr)) {
							String[] fileTos = fileToStr.split(",");
							if (fileTos != null && fileTos.length > 0) {
								for (String fileTo : fileTos) {
									if (StringUtils.isNotEmpty(fileTo)) {
										teamList.add(fileTo);
									}
								}
							}

						}
						
						if (StringUtils.isNotBlank(fileCcStr)) {
							String[] fileCcs = fileCcStr.split(",");
							if (fileCcs != null && fileCcs.length > 0) {
								for (String fileCc : fileCcs) {
									if (StringUtils.isNotBlank(fileCc)) {
										teamList.add(fileCc);
									}
								}
							}

						}

						JSONArray attachmentList = CMSUtil.getAttach(bo.getId(), "ZW", "ATTFILE");
						
						String createUserId = bo.getString("USERID");
						// 调用发布cms数据的方法
						String cmsid = CMSUtil.createUrlCmsData(pec.getUserContext(), moduleid,
								pec.getProcessInstance().getId(), taskInstId, formDefId, title, attachmentList,
								teamList, boName, "PDFFILE", "ATTFILE", createUserId);
						String updateSql = " UPDATE " + boName
								+ " SET CMSMODELID =:CMSMODELID,REFCMSID=:REFCMSID WHERE ID = :ID";
						Map<String, Object> updateMap = new HashMap<String, Object>();
						updateMap.put("CMSMODELID", moduleid);
						updateMap.put("REFCMSID", cmsid);
						updateMap.put("ID", bo.getId());
						DBSql.update(updateSql, updateMap);
					}
				}
			}
		}
		return true;
	}
}
